<!-- CustomSelect.vue -->
<template>
  <div class="custom-select-wrapper" ref="wrapper">
    <div 
      class="selected-option"
      :class="{ 'select-open': isOpen }"
      @click="toggleDropdown"
   
      tabindex="0"
    >
      <slot name="selected" :selected="selectedOption">
        {{ selectedLabel }}
      </slot>
    </div>

    <transition name="slide-fade">
      <div v-show="isOpen" class="options-list">
        <ul>
          <li
            v-for="(option, index) in options"
            :key="option[selectConfig.id]"
            :class="{ 
              'selected': isSelected(option),
              'highlighted': highlightedIndex === index
            }"
            @click="selectOption(option)"
            @mouseenter="highlightedIndex = index"
          >
            <slot name="option" :option="option">
              {{ option[selectConfig.label] }}
            </slot>
          </li>
        </ul>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount,nextTick  } from 'vue'

const props = defineProps({
  currentUserId: {
    type: [Object, String, Number],
    default: null
  },
  options: {
    type: Array,
    required: true
  },
  selectConfig: {
    type: Object,
    default: () => ({
      label: 'label',
      id: 'id'
    })
  }
})

const emit = defineEmits(['update:currentUserId', 'change'])

const isOpen = ref(false)
const highlightedIndex = ref(-1)
const wrapper = ref(null)

// 当前选中项
const selectedOption = computed(() => {
  console.log(props.options,props.currentUserId)
  return props.options.find(
    opt => opt[props.selectConfig.id] === props.currentUserId
  ) || {}
})

// 显示标签
const selectedLabel = computed(() => {
  console.log("selectedOption",selectedOption.value)
  return selectedOption.value[props.selectConfig.label] || '请选择'
})

// 切换下拉框
const toggleDropdown = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    highlightedIndex.value = props.options.findIndex(
      opt => opt[props.selectConfig.id] === props.currentUserId
    )
  }
}

// 选择选项
const selectOption = (option) => {
  let key = props.selectConfig.id
  const value = option[key]
  // console.log(option,value)
  // selectedLabel.value = option[props.selectConfig.label]
  emit('update:currentUserId', value)
  console.log('props.currentUserId',props.currentUserId,value)
  emit('change', option)
  isOpen.value = false
}

// 判断是否选中
const isSelected = (option) => {
  return option[props.selectConfig.id] === props.currentUserId
}



// 点击外部关闭
const clickOutsideHandler = (e) => {
  if (!wrapper.value?.contains(e.target)) {
    isOpen.value = false
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', clickOutsideHandler)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', clickOutsideHandler)
})

// 监听选项变化
watch(isOpen, (newVal) => {
  if (newVal) {
    // 滚动到选中项
    nextTick(() => {
      const selectedEl = wrapper.value.querySelector('.selected')
      if (selectedEl) {
        selectedEl.scrollIntoView({ block: 'nearest' })
      }
    })
  }
})
</script>

<style scoped>
.custom-select-wrapper {
  position: relative;
  width: 200px;
  display: inline-block;

  font-family: Arial, sans-serif;
}

.selected-option {
  padding: 2px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  height: 20px;
  background: white;
  transition: border-color 0.3s;
}

.selected-option:hover {
  border-color: #409eff;
}

.selected-option.select-open {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64,158,255,.2);
}

.options-list {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 4px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  z-index: 1000;
}

.options-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
li{
  height: 20px;
}
.options-list li {
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.options-list li:hover {
  background-color: #f5f7fa;
}

.options-list li.highlighted {
  background-color: #f5f7fa;
}

.options-list li.selected {
  color: #409eff;
  font-weight: bold;
  background-color: #ecf5ff;
}

/* 过渡动画 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>